package com.kanche.bigbaby.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.kanche.bigbaby.AppConfig;
import com.kanche.bigbaby.BigBabyApplication;
import com.kanche.bigbaby.R;
import com.kanche.bigbaby.activity.VehicleDetailsActivity;
import com.kanche.bigbaby.adapter.VehicleListAdapter;
import com.kanche.bigbaby.bean.ResponseBaseBean;
import com.kanche.bigbaby.collection.KKCheDBHelper;
import com.kanche.bigbaby.collection.domain.Vehicle;
import com.kanche.bigbaby.support.base.BaseFragment;
import com.kanche.bigbaby.support.ddlv.ToastUtils;
import com.kanche.bigbaby.support.smlistview.SwipeMenu;
import com.kanche.bigbaby.support.smlistview.SwipeMenuCreator;
import com.kanche.bigbaby.support.smlistview.SwipeMenuItem;
import com.kanche.bigbaby.support.smlistview.SwipeMenuListView;
import com.kanche.bigbaby.support.utils.ViewUtility;

import java.util.ArrayList;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.Options;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import uk.co.senab.actionbarpulltorefresh.library.viewdelegates.AbsListViewDelegate;

/**
 * Created by Chenshao_Young on 15/5/19.
 */
public class CollectionFragment extends BaseFragment implements SwipeMenuListView.OnLoadMoreListener,OnRefreshListener {

    View view;
    SwipeMenuListView lv;
    PullToRefreshLayout layout;

    VehicleListAdapter vehicleListAdapter;
    List<Vehicle> vehicleList = new ArrayList<>();
    KKCheDBHelper dbHelper;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_collection, container, false);
        lv = justFindIt(view, R.id.smlv_collection);
        layout = justFindIt(view, R.id.srl_collect);


        ActionBarPullToRefresh.from(getActivity())
                .options(Options.create()
                        // Here we make the refresh scroll distance to 75% of the GridView height
                        .scrollDistance(.50f)
                                // Here we define a custom header layout which will be inflated and used
//                        .headerLayout(R.layout.customised_header)
                                // Here we define a custom header transformer which will alter the header
                                // based on the current pull-to-refresh state
//                        .headerTransformer(new CustomisedHeaderTransformer())
                        .build())
                .allChildrenArePullable()
                .listener(this)
                        // Here we'll set a custom ViewDelegate
                .useViewDelegate(GridView.class, new AbsListViewDelegate())
                .setup(layout);

        lv.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
            }

            @Override
            public void onSwipeEnd(int position) {
            }
        });
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dbHelper = new KKCheDBHelper(getActivity());
        vehicleList = dbHelper.findAllLocalVehicles();
        vehicleListAdapter = new VehicleListAdapter(getActivity(),vehicleList);

        lv.setAdapter(vehicleListAdapter);
        lv.setmOnLoadMoreListener(this);

        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem uploadItem = new SwipeMenuItem(context);
                uploadItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE)));
                uploadItem.setWidth(90);
                uploadItem.setTitle("上传");
                uploadItem.setTitleSize(18);
                uploadItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(uploadItem);

                SwipeMenuItem editItem = new SwipeMenuItem(context);
                editItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                editItem.setWidth(90);
                editItem.setTitle("修改");
                editItem.setTitleSize(18);
                editItem.setTitleColor(Color.BLACK);
                editItem.setIcon(R.drawable.ic_delete);
                menu.addMenuItem(editItem);
            }
        };
        lv.setMenuCreator(creator);


        lv.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
//                ApplicationInfo item = mAppList.get(position);
                switch (index) {
                    case 0:
                        ToastUtils.show(getActivity(), "上传中。。");
                        getBBService().upLoadVehicle(vehicleList.get(position), new Callback<ResponseBaseBean>() {
                            @Override
                            public void success(ResponseBaseBean responseBaseBean, Response response) {

                        ToastUtils.show(getActivity(), "success");
                            }

                            @Override
                            public void failure(RetrofitError error) {
                        ToastUtils.show(getActivity(), "failed。。"+error.getKind() + error.getMessage());

                            }
                        });
                        break;
                    case 1:
                        ToastUtils.show(getActivity(), "修改。。");

                        break;
                }
                return false;
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ViewUtility.intent_startActivity(getActivity(), VehicleDetailsActivity.class);
            }
        });

    }

    public static CollectionFragment newInstance(){
        Bundle arg = new Bundle();
        arg.putString(FRAGMENT_NAME,CollectionFragment.class.getSimpleName());

        CollectionFragment fragment = new CollectionFragment();
        fragment.setArguments(arg);
        return fragment;
    }

    @Override
    public void loadMore() {

        ToastUtils.show(getActivity(),"loadmore..");
    }

    @Override
    public void onRefreshStarted(View view) {

        if (vehicleListAdapter != null) {
            vehicleList = dbHelper.findAllLocalVehicles();
            vehicleListAdapter.setList(vehicleList);
            vehicleListAdapter.notifyDataSetChanged();
        }
        layout.postDelayed(new Runnable() {
            @Override
            public void run() {
                layout.setRefreshComplete();
            }
        },200);
    }

    //

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == AppConfig.MainToStep1 && resultCode == Activity.RESULT_OK){

        }
        if (vehicleListAdapter != null) {
            vehicleList = dbHelper.findAllLocalVehicles();
            vehicleListAdapter.setList(vehicleList);
            vehicleListAdapter.notifyDataSetChanged();
        }
//        if (requestCode == Consts.DISTRIBUTION_DIALOG && resultCode == Activity.RESULT_OK) {
//            long rowId = data.getLongExtra("rowId", 0L);
//            ArrayList<CharSequence> ids = data.getCharSequenceArrayListExtra("shareAccounts");
//            Vehicle vehicle = dbHelper.findVehicleByRowId(rowId);
//            startUploadVehicle(vehicle, VehicleUploadTask.UPLOAD_AND_DISTRIBUTE_VEHICLE, ids);
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(BigBabyApplication.NeedRefresh_CollectionFrag){
            onRefreshStarted(null);
            BigBabyApplication.NeedRefresh_CollectionFrag = false;
        }
    }
}
